// 通常可以吧 baseUrl 单独放在一个 js 文件了
import config from "@/config/index";
import utils from "@/utils/utils";
import useCounterStore from "@/stores/counter";

const request = (options = {}) => {
  // 在这里可以对请求头进行一些设置
  options.header = {
    "content-type": "application/json",
  }
  let ycMpParams = uni.getStorageSync('ycMpParams')
  if (ycMpParams && ycMpParams.token) {
    options.header['Authorization'] = `Bearer ${ycMpParams.token}`
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.baseUrl + options.url || '',
      method: (options.type ? options.type : options.method.toLocaleUpperCase()) || 'GET',
      data: options.data || {},
      header: options.header || {}
    }).then(data => {
      if (data.data.code == 200) {
        resolve(data.data.data);
      } else if (data.data.code == 401) { //登录过期
        useCounterStore().setYcParams("token", null)
        //uni.clearStorageSync();//同步清理缓存
        utils.showToast(data.data.msg)
        reject(data.data.msg)
      }
      else {
        utils.showToast(data.data.msg)
        reject(data.data.msg)
      }
    }).catch(error => {
      reject(error)
    })
  });
}

const get = (url, data, options = {}) => {
  options.type = 'GET';
  options.data = data;
  options.url = url;
  return request(options)
}

const post = (url, data, options = {}) => {
  options.type = 'POST';
  options.data = data;
  options.url = url;
  return request(options)
}


export default {
  request,
  get,
  post
}
